import { DomainObject, Project, Schemas } from '@/types/domain_models'
import { upperFirst, camelCase, kebabCase, snakeCase } from 'lodash'

/**
 * 默认的项目配置
 */
const BASE_PROJECT: Partial<Project> = {
  name: 'tianzhi-java-demo',
  packageName: 'com.tianzhi.v1',
  desc: 'yeoman tianzhi java 生成的项目',
  version: '1.0.0',
}

/**
 * 合并默认配置，处理一些参数，赋予一些默认值
 */
export function initProject(domainObject: DomainObject): DomainObject {
  const resultSchemas: Schemas = {}
  Object.entries(domainObject.schemas).forEach(([key, schema]) => {
    const camelCaseName = camelCase(key)
    const upperFirstCamelCaseName = upperFirst(camelCaseName)
    const snakeCameName = snakeCase(key)
    const kebabCaseName = kebabCase(key)
    const required = schema.required
    const primarykey = schema.primarykey || []
    const properties = Object.entries(schema.properties)
      .map(([pKey, property], index) => {
        return {
          ...property,
          pKey,
          primaryKey: primarykey.length ? primarykey[0] === pKey : index === 0,
          required: required?.some((requiredProperty) => requiredProperty === pKey) ?? false,
          camelCaseName: camelCase(pKey),
          snakeCameName: snakeCase(pKey),
        }
      })
      .reduce((prev, next) => {
        prev[next.pKey] = next
        return prev
      }, {})
    resultSchemas[key] = {
      type: schema.type,
      camelCaseName,
      upperFirstCamelCaseName,
      snakeCameName,
      kebabCaseName,
      required,
      properties,
    }
  })
  return {
    projeect: { ...BASE_PROJECT, ...domainObject.projeect },
    database: domainObject.database,
    schemas: resultSchemas,
  }
}
